package cn.imokay.juc.future;

import java.util.concurrent.*;

public class FutureThreadPoolDemo {
    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(3);
        FutureTask<String> task1 = new FutureTask<>(() -> "999");
        FutureTask<String> task2 = new FutureTask<>(() -> "998889");
        FutureTask<String> task3 = new FutureTask<>(() -> "9sdf98889");
        pool.submit(task1);
        pool.submit(task2);
        pool.submit(task3);
        try {
            //get是个阻塞方法，不见不散，尽可能放到后面调用
            System.out.println(task1.get());
            //可以利用超时防止阻塞，但是会跑错，不优雅
            System.out.println(task2.get(3, TimeUnit.SECONDS));
            //轮询，给提示信息，但是会浪费cpu资源
            while(true) {
                if (task3.isDone()) {
                    System.out.println(task3.get());
                }else{
                    System.out.println("...");
                }

            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        } catch (TimeoutException e) {
            throw new RuntimeException(e);
        } finally {
            pool.shutdown();
        }
    }
}
